package dao;

import common.Select;
import common.Topic;
import common.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class GetTopic {
    private static Connection conn=DataBaseConnect.getConn();
    private static String sql="select id,courseid,title,createdate,deaddate,createtime,deadtime from assignment where courseid=?";
    private static String sql2="select content from topic where assignmentid=?";
    private static PreparedStatement pstmt,pstmt2;

    static {
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt2=conn.prepareStatement(sql2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Vector<Topic> getTopic(String courseid, Vector<User> student){
        Vector<Topic> topics=new Vector<>();
        try {
            pstmt.setString(1,courseid);
            ResultSet rs=pstmt.executeQuery();
            while(rs.next()){
                pstmt2.setString(1,rs.getString(1));
                ResultSet qrs=pstmt2.executeQuery();
                Vector<String> questions=new Vector<>();
                while (qrs.next()){
                    questions.add(qrs.getString(1));
                }
                Topic topic=new Topic(rs.getString(3),questions,rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7));
                topic.setTopicid(rs.getString(1));
                //homework
                for(User user:student){
                    topic.getHomeworks().put(user,GetStuHW.getStuHW(topic.getTopicid(),user.getId()));
                }
                topics.add(topic);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return topics;
    }
    public static Vector<Topic> getTopic(String courseid,String studentid){
        Vector<Topic> topics=new Vector<>();
        try {
            pstmt.setString(1,courseid);
            ResultSet rs=pstmt.executeQuery();
            while(rs.next()){
                pstmt2.setString(1,rs.getString(1));
                ResultSet qrs=pstmt2.executeQuery();
                Vector<String> questions=new Vector<>();
                while (qrs.next()){
                    questions.add(qrs.getString(1));
                }
                Topic topic=new Topic(rs.getString(3),questions,rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7));
                topic.setTopicid(rs.getString(1));
                //homework
                topic.setHomework(GetStuHW.getStuHW(topic.getTopicid(),studentid));
                topics.add(topic);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return topics;
    }
}
